<template>
  <div>
    <div v-for="(item, index) in items" :key="index" style="display: flex; gap: 8px; align-items: center; margin-bottom: 6px">
      <el-input v-model="items[index]" placeholder="请输入值" />
      <el-button type="danger" @click="remove(index)">删除</el-button>
    </div>
    <el-button type="primary" plain @click="add">添加</el-button>
    <div class="dk-help" style="margin-top: 6px">每行一个值，自动按 'a','b' 格式保存</div>
  </div>
</template>

<script setup>
import { ref, watch, defineEmits, defineProps } from 'vue'

const props = defineProps({
  modelValue: { type: String, default: '' }
})

const emit = defineEmits(['update:modelValue'])

const items = ref([])

function parseToArray(input) {
  if (!input || typeof input !== 'string') return []
  const result = []
  const regex = /'([^']*)'/g
  let m
  while ((m = regex.exec(input)) !== null) {
    result.push(m[1])
  }
  if (!result.length) {
    return input
      .split(',')
      .map((s) => s.trim())
      .filter((s) => s.length > 0)
  }
  return result
}

function toModelValue(arr) {
  const filtered = arr.map((s) => s.trim()).filter((s) => s.length > 0)
  return filtered
    .map((v) => (v.includes("'") ? v.replace(/'/g, "\\'") : v))
    .map((v) => `'${v}'`)
    .join(',')
}

watch(
  () => props.modelValue,
  (nv) => {
    items.value = parseToArray(nv)
    if (!items.value.length) {
      items.value.push('')
    }
  },
  { immediate: true }
)

watch(
  items,
  (arr) => {
    emit('update:modelValue', toModelValue(arr))
  },
  { deep: true }
)

function add() {
  items.value.push('')
}

function remove(index) {
  items.value.splice(index, 1)
}
</script>

<style scoped></style>
